import './Devextreme.scss'
import 'devextreme/dist/css/dx.material.blue.light.compact.css'

import { useMount } from 'ahooks'
import { Workbook } from 'exceljs'
import { saveAs } from 'file-saver'
import { Skeleton, App } from 'antd'
import { useRequest } from 'alova/client'
import { useCallback, useMemo, useState } from 'react'
import { exportDataGrid } from 'devextreme/excel_exporter'
import { exportPivotGrid } from 'devextreme/excel_exporter'

import {
    DataGrid,
    Column,
    Lookup,
    Scrolling,
    FilterRow,
    HeaderFilter,
    SearchPanel,
    GroupPanel,
    Grouping,
    ColumnFixing,
    Summary,
    GroupItem,
    TotalItem,
    Sorting,
    Selection,
    RowDragging,
    Export,
    LoadPanel,
    ColumnChooser,
    ColumnChooserSearch,
    ColumnChooserSelection,
    Position,
    Paging
} from 'devextreme-react/data-grid'
import { TreeList } from 'devextreme-react/tree-list'

import {
    PivotGrid,
    FieldChooser,
    FieldPanel,
    StateStoring,
} from 'devextreme-react/pivot-grid'

import PivotGridDataSource from 'devextreme/ui/pivot_grid/data_source'

import { API_Mapping, Http } from '../Utils/Api'

import { FieldMapping } from '../Config/Mapping'
import { ButtonMapping } from './ButtonMapping'

import { devChartsStore } from '../Config/zustand'
import { useRef } from 'react'
import { useEffect } from 'react'

import { numberFormatting } from '../Utils'

// 数据表格
export const DevextremeDataGrid = ({ dataSource, fields, DataConfig, ColumnOptions, DevEvent, selectRowkeys }) => {
    const [fieldsMapping, setFieldsMapping] = useState()

    // 拖拽回调函数
    const onReorder = useCallback(
        (e) => {
            const visibleRows = e.component.getVisibleRows();
            const newTasks = [...dataSource];
            const toIndex = newTasks.findIndex((item) => item.id === visibleRows[e.toIndex].data.id);
            const fromIndex = newTasks.findIndex((item) => item.id === e.itemData.id);
            newTasks.splice(fromIndex, 1);
            newTasks.splice(toIndex, 0, e.itemData);
            // setDataSource(newTasks);
        },
        [dataSource]
    )
    // 导出函数
    const onExporting = (e) => {
        const workbook = new Workbook()
        const worksheet = workbook.addWorksheet('Main sheet')
        exportDataGrid({ component: e.component, worksheet, autoFilterEnabled: true }).then(() =>
            workbook.xlsx.writeBuffer().then((buffer) => saveAs(new Blob([buffer], { type: 'application/octet-stream' }), 'DataGrid.xlsx'))
        )
    }
    // 更改单元格样式
    const onCellPrepared = e => {
        // console.log(e)
        // if (e.column.dataField === "uuid") {
        //     console.log(e.rowType)  // 头部  单元格 底部统计
        //     if (e.data?.num01 > 3000) e.cellElement.style.cssText = "color: white; background-color: red"  // e.cellElement.classList.add("my-class")
        //     if (!e.data?.num01) e.cellElement.style.cssText = "color: white; background-color: #000"
        // }
    }
    // 更改行样式
    const onRowPrepared = e => {
        if (e.rowType === "data") {
            if (e.data.num01 > 4000) {
                e.rowElement.style.cssText = "color: white; background-color: red" //e.rowElement.classList.add("my-class");
            }
        }
    }

    const onSelectionChanged = e => {
        DevEvent.emit({ type: 'onSelectionChanged', data: e.selectedRowKeys })
    }

    useMount(async () => {
        const promises = fields.map(async item => {
            const { isMapping, mappingType, mappingData } = item
            if (isMapping) {
                if (mappingType === 'DataMapping') item.lookupMapping = FieldMapping[mappingData]
                if (mappingType === 'ApiMapping') item.lookupMapping = await API_Mapping[mappingData]()
            }
        })
        await Promise.all(promises)
        setFieldsMapping(fields)
    })

    return (
        <div className='DevextremeDataGrid' >
            {fieldsMapping ?
                <DataGrid
                    id={new Date().getTime()}
                    keyExpr='uuid' // 主键
                    dataSource={dataSource} // 数据
                    defaultSelectedRowKeys={selectRowkeys}
                    allowColumnReordering={DataConfig.allowColumnReordering}
                    showColumnHeaders={DataConfig.showColumnHeaders}
                    columnMinWidth={DataConfig.columnMinWidth}
                    columnAutoWidth={DataConfig.columnAutoWidth}
                    allowColumnResizing={DataConfig.allowColumnResizing}
                    columnResizingMode={DataConfig.columnResizingMode}
                    repaintChangesOnly={DataConfig.repaintChangesOnly}
                    focusedRowEnabled={DataConfig.focusedRowEnabled}
                    showBorders={DataConfig.showBorders}
                    showRowLines={DataConfig.showRowLines}
                    showColumnLines={DataConfig.showColumnLines}
                    rowAlternationEnabled={DataConfig.rowAlternationEnabled}
                    onExporting={onExporting}
                    onCellPrepared={onCellPrepared}
                    onRowPrepared={onRowPrepared}
                    onSelectionChanged={onSelectionChanged}
                >
                    {fieldsMapping.map(item =>
                        <Column
                            key={item.dataField}
                            visible={item.visible}
                            caption={item.caption}
                            dataField={item.dataField}
                            cssClass={item.cssClass}
                            alignment={item.alignment}
                            dataType={item.dataType}
                            format={numberFormatting(item.dataType, item.format)}
                            minWidth={item.minWidth}
                            width={item.width}
                            fixed={item.fixed}
                            fixedPosition={item.fixedPosition}
                            allowResizing={item.allowResizing}
                            allowFiltering={item.allowFiltering}
                            allowHeaderFiltering={item.allowHeaderFiltering}
                            allowReordering={item.allowReordering}
                            autoExpandGroup={item.autoExpandGroup}
                            showInColumnChooser={item.showInColumnChooser}
                            allowGrouping={item.allowGrouping}
                        // groupIndex={item.groupIndex}
                        // allowSorting={item.allowSorting}
                        // defaultSortIndex={item.defaultSortIndex}
                        // defaultSortOrder={item.defaultSortOrder}
                        // customizeText
                        // calculateCellValue
                        >
                            {item.isMapping && <Lookup dataSource={item.lookupMapping} valueExpr={item.mappingValue} displayExpr={item.mappingLable} />}
                        </Column>
                    )}
                    {DataConfig.columnDlyState &&
                        <Column
                            width={DataConfig.columnDlyWidth}
                            caption='操作'
                            cssClass="employee"
                            showInColumnChooser={false}
                            fixed={true}
                            fixedPosition='right'
                            alignment='center'
                            cellRender={(e) => <>
                                {ColumnOptions({ data: e.data, fields }).map((item, index) => <ButtonMapping key={index} config={item} />)}
                            </>}
                        />
                    }
                    <ColumnFixing enabled={DataConfig.columnFixing} />
                    <ColumnChooser
                        enabled={DataConfig.columnChooser}
                        mode={DataConfig.columnChooserMode}
                        height={600}
                    >
                        <Position my="right top" at="right bottom" of=".dx-datagrid-column-chooser-button" />
                        <ColumnChooserSearch
                            enabled={DataConfig.columnChooserSearch}
                            editorOptions={{ placeholder: DataConfig.columnChooserSearchPlaceholder }}
                        />
                        <ColumnChooserSelection
                            allowSelectAll={DataConfig.columnChooserSelectionAll}
                            selectByClick={DataConfig.columnChooserSelectionClick}
                            recursive={DataConfig.columnChooserSelectionRecursive}
                        />
                    </ColumnChooser>
                    <FilterRow visible={DataConfig.filterRow} applyFilter={DataConfig.filterRowApplyFilter} />
                    <SearchPanel visible={DataConfig.searchPanel} />
                    <HeaderFilter visible={DataConfig.headerFilter} />
                    <GroupPanel
                        visible={DataConfig.groupPanel}
                        autoExpandAll={DataConfig.groupPanelAutoExpandAll}
                        allowColumnDragging={DataConfig.groupPanelAllowColumnDragging}
                    />
                    <Grouping
                        expandMode={DataConfig.groupingExpandMode}
                        contextMenuEnabled={DataConfig.groupingContextMenuEnabled}
                        autoExpandAll={DataConfig.groupingAutoExpandAll}
                        allowCollapsing={DataConfig.groupingAllowCollapsing}
                    />
                    <Sorting mode={DataConfig.sorting} />
                    <Selection
                        mode={DataConfig.selectionMode}
                        allowSelectAll={DataConfig.selectionAllowSelectAll}
                        selectAllMode={DataConfig.selectionSelectAllMode}
                        showCheckBoxesMode={DataConfig.selectionShowCheckBoxesMode}
                    />
                    <RowDragging
                        allowReordering={DataConfig.rowDragging}
                        showDragIcons={DataConfig.rowDraggingShowDragIcons}
                        onReorder={onReorder}
                    />
                    <Export enabled={DataConfig.export} allowExportSelectedData={DataConfig.exportAllowExportSelectedData} />
                    <LoadPanel enabled={DataConfig.loadPanel} />
                    <Summary>
                        {DataConfig.totalSummary && DataConfig.totalSummary.map((sum, index) =>
                            <TotalItem
                                key={index}
                                column={sum.column}
                                summaryType={sum.summaryType}
                                showInColumn={sum.showInColumn}
                                alignment={sum.alignment}
                                valueFormat={sum?.valueFormat || ''}
                                displayFormat={`${sum?.customizeText || ''}{0}`}
                            />
                        )}
                        {DataConfig.groupSummary && DataConfig.groupSummary.map((sum, index) =>
                            <GroupItem
                                key={index}
                                column={sum.column}
                                summaryType={sum.summaryType}
                                valueFormat={sum?.valueFormat || ''}
                                displayFormat={`${sum?.customizeText || ''}{0}`}
                            />
                        )}
                    </Summary>
                    <Scrolling rowRenderingMode="virtual" />
                    <Paging defaultPageSize={1000000} />
                </DataGrid> :
                <Skeleton active />
            }
        </div>
    );
}

// 多层表头
export const DevextremeMultilayerGrid = ({ dataSource, fields, DataConfig, ColumnOptions, DevEvent, selectRowkeys }) => {
    const [fieldsMapping, setFieldsMapping] = useState()

    // 拖拽回调函数
    const onReorder = useCallback(
        (e) => {
            const visibleRows = e.component.getVisibleRows();
            const newTasks = [...dataSource];
            const toIndex = newTasks.findIndex((item) => item.id === visibleRows[e.toIndex].data.id);
            const fromIndex = newTasks.findIndex((item) => item.id === e.itemData.id);
            newTasks.splice(fromIndex, 1);
            newTasks.splice(toIndex, 0, e.itemData);
            // setDataSource(newTasks);
        },
        [dataSource]
    )
    // 导出函数
    const onExporting = (e) => {
        const workbook = new Workbook()
        const worksheet = workbook.addWorksheet('Main sheet')
        exportDataGrid({ component: e.component, worksheet, autoFilterEnabled: true }).then(() =>
            workbook.xlsx.writeBuffer().then((buffer) => saveAs(new Blob([buffer], { type: 'application/octet-stream' }), 'DataGrid.xlsx'))
        )
    }
    // 更改单元格样式
    const onCellPrepared = e => {
        // console.log(e)
        // if (e.column.dataField === "uuid") {
        //     console.log(e.rowType)  // 头部  单元格 底部统计
        //     if (e.data?.num01 > 3000) e.cellElement.style.cssText = "color: white; background-color: red"  // e.cellElement.classList.add("my-class")
        //     if (!e.data?.num01) e.cellElement.style.cssText = "color: white; background-color: #000"
        // }
    }
    // 更改行样式
    const onRowPrepared = e => {
        if (e.rowType === "data") {
            if (e.data.num01 > 4000) {
                e.rowElement.style.cssText = "color: white; background-color: red" //e.rowElement.classList.add("my-class");
            }
        }
    }

    const onSelectionChanged = e => {
        DevEvent.emit({ type: 'onSelectionChanged', data: e.selectedRowKeys })
    }

    useMount(async () => {
        const promises = fields.map(async item => {
            const { isMapping, mappingType, mappingData } = item
            if (isMapping) {
                if (mappingType === 'DataMapping') item.lookupMapping = FieldMapping[mappingData]
                if (mappingType === 'ApiMapping') item.lookupMapping = await API_Mapping[mappingData]()
            }
        })
        await Promise.all(promises)
        setFieldsMapping(fields)
    })

    return (
        <div className='DevextremeDataGrid' >
            {fieldsMapping ?
                <DataGrid
                    id={new Date().getTime()}
                    keyExpr='uuid' // 主键
                    dataSource={dataSource} // 数据
                    defaultSelectedRowKeys={selectRowkeys}
                    allowColumnReordering={DataConfig.allowColumnReordering}
                    showColumnHeaders={DataConfig.showColumnHeaders}
                    columnMinWidth={DataConfig.columnMinWidth}
                    columnAutoWidth={DataConfig.columnAutoWidth}
                    allowColumnResizing={DataConfig.allowColumnResizing}
                    columnResizingMode={DataConfig.columnResizingMode}
                    repaintChangesOnly={DataConfig.repaintChangesOnly}
                    focusedRowEnabled={DataConfig.focusedRowEnabled}
                    showBorders={DataConfig.showBorders}
                    showRowLines={DataConfig.showRowLines}
                    showColumnLines={DataConfig.showColumnLines}
                    rowAlternationEnabled={DataConfig.rowAlternationEnabled}
                    onExporting={onExporting}
                    onCellPrepared={onCellPrepared}
                    onRowPrepared={onRowPrepared}
                    onSelectionChanged={onSelectionChanged}
                >
                    {DataConfig.multilayerConfig && DataConfig.multilayerConfig.map((itemA) => {
                        const { key, dataField, caption, children } = itemA
                        const propo = dataField ? fieldsMapping.find(v => v.dataField === dataField) : { caption }
                        if (propo) {
                            return (
                                <Column
                                    key={key}
                                    visible={propo.visible}
                                    caption={propo.caption}
                                    dataField={propo.dataField}
                                    cssClass={propo.cssClass}
                                    alignment={propo.alignment || 'center'}
                                    dataType={propo.dataType}
                                    format={numberFormatting(propo.dataType, propo.format)}
                                    minWidth={propo.minWidth}
                                    // width={propo.width}
                                    fixed={propo.fixed}
                                    fixedPosition={propo.fixedPosition}
                                    allowResizing={propo.allowResizing}
                                    allowFiltering={propo.allowFiltering}
                                    allowHeaderFiltering={propo.allowHeaderFiltering}
                                    allowReordering={propo.allowReordering}
                                    autoExpandGroup={propo.autoExpandGroup}
                                    showInColumnChooser={propo.showInColumnChooser}
                                    allowGrouping={propo.allowGrouping}
                                >
                                    {children && children.map((itemB,) => {
                                        const { key, dataField, caption, children } = itemB
                                        const propo = dataField ? fieldsMapping.find(v => v.dataField === dataField) : { caption }
                                        return (
                                            <Column
                                                key={key}
                                                visible={propo.visible}
                                                caption={propo.caption}
                                                dataField={propo.dataField}
                                                cssClass={propo.cssClass}
                                                alignment={propo.alignment || 'center'}
                                                dataType={propo.dataType}
                                                format={propo.format === 'currency' ? { style: "currency", currency: "CNY", useGrouping: true } : propo.format}
                                                minWidth={propo.minWidth}
                                                // width={propo.width}
                                                fixed={propo.fixed}
                                                fixedPosition={propo.fixedPosition}
                                                allowResizing={propo.allowResizing}
                                                allowFiltering={propo.allowFiltering}
                                                allowHeaderFiltering={propo.allowHeaderFiltering}
                                                allowReordering={propo.allowReordering}
                                                autoExpandGroup={propo.autoExpandGroup}
                                                showInColumnChooser={propo.showInColumnChooser}
                                                allowGrouping={propo.allowGrouping}
                                            >
                                                {children && children.map((itemC) => {
                                                    const { key, dataField, caption, children } = itemC
                                                    const propo = dataField ? fieldsMapping.find(v => v.dataField === dataField) : { caption }
                                                    return (
                                                        <Column
                                                            key={key}
                                                            visible={propo.visible}
                                                            caption={propo.caption}
                                                            dataField={propo.dataField}
                                                            cssClass={propo.cssClass}
                                                            alignment={propo.alignment || 'center'}
                                                            dataType={propo.dataType}
                                                            format={propo.format === 'currency' ? { style: "currency", currency: "CNY", useGrouping: true } : propo.format}
                                                            minWidth={propo.minWidth}
                                                            // width={propo.width}
                                                            fixed={propo.fixed}
                                                            fixedPosition={propo.fixedPosition}
                                                            allowResizing={propo.allowResizing}
                                                            allowFiltering={propo.allowFiltering}
                                                            allowHeaderFiltering={propo.allowHeaderFiltering}
                                                            allowReordering={propo.allowReordering}
                                                            autoExpandGroup={propo.autoExpandGroup}
                                                            showInColumnChooser={propo.showInColumnChooser}
                                                            allowGrouping={propo.allowGrouping}
                                                        >
                                                            {children && children.map((itemD) => {
                                                                const { key, dataField, caption, children } = itemD
                                                                const propo = dataField ? fieldsMapping.find(v => v.dataField === dataField) : { caption }
                                                                return (
                                                                    <Column
                                                                        key={key}
                                                                        visible={propo.visible}
                                                                        caption={propo.caption}
                                                                        dataField={propo.dataField}
                                                                        cssClass={propo.cssClass}
                                                                        alignment={propo.alignment || 'center'}
                                                                        dataType={propo.dataType}
                                                                        format={propo.format === 'currency' ? { style: "currency", currency: "CNY", useGrouping: true } : propo.format}
                                                                        minWidth={propo.minWidth}
                                                                        // width={propo.width}
                                                                        fixed={propo.fixed}
                                                                        fixedPosition={propo.fixedPosition}
                                                                        allowResizing={propo.allowResizing}
                                                                        allowFiltering={propo.allowFiltering}
                                                                        allowHeaderFiltering={propo.allowHeaderFiltering}
                                                                        allowReordering={propo.allowReordering}
                                                                        autoExpandGroup={propo.autoExpandGroup}
                                                                        showInColumnChooser={propo.showInColumnChooser}
                                                                        allowGrouping={propo.allowGrouping}
                                                                    > </Column>
                                                                )
                                                            })}
                                                        </Column>
                                                    )
                                                })}
                                            </Column>
                                        )
                                    })}
                                </Column>
                            )
                        }
                    })}
                    {DataConfig.columnDlyState &&
                        <Column
                            caption='操作'
                            cssClass="employee"
                            showInColumnChooser={false}
                            fixed={true}
                            width={DataConfig.columnDlyWidth}
                            fixedPosition='right'
                            alignment='center'
                            cellRender={(e) => <>
                                {ColumnOptions({ data: e.data, fields }).map((item, index) => <ButtonMapping key={index} config={item} />)}
                            </>}
                        />
                    }
                    <ColumnFixing enabled={DataConfig.columnFixing} />
                    <ColumnChooser
                        enabled={DataConfig.columnChooser}
                        mode={DataConfig.columnChooserMode}
                        height={600}
                    >
                        <Position my="right top" at="right bottom" of=".dx-datagrid-column-chooser-button" />
                        <ColumnChooserSearch
                            enabled={DataConfig.columnChooserSearch}
                            editorOptions={{ placeholder: DataConfig.columnChooserSearchPlaceholder }}
                        />
                        <ColumnChooserSelection
                            allowSelectAll={DataConfig.columnChooserSelectionAll}
                            selectByClick={DataConfig.columnChooserSelectionClick}
                            recursive={DataConfig.columnChooserSelectionRecursive}
                        />
                    </ColumnChooser>
                    <FilterRow visible={DataConfig.filterRow} applyFilter={DataConfig.filterRowApplyFilter} />
                    <SearchPanel visible={DataConfig.searchPanel} />
                    <HeaderFilter visible={DataConfig.headerFilter} />
                    <GroupPanel
                        visible={DataConfig.groupPanel}
                        autoExpandAll={DataConfig.groupPanelAutoExpandAll}
                        allowColumnDragging={DataConfig.groupPanelAllowColumnDragging}
                    />
                    <Grouping
                        expandMode={DataConfig.groupingExpandMode}
                        contextMenuEnabled={DataConfig.groupingContextMenuEnabled}
                        autoExpandAll={DataConfig.groupingAutoExpandAll}
                        allowCollapsing={DataConfig.groupingAllowCollapsing}
                    />
                    <Sorting mode={DataConfig.sorting} />
                    <Selection
                        mode={DataConfig.selectionMode}
                        allowSelectAll={DataConfig.selectionAllowSelectAll}
                        selectAllMode={DataConfig.selectionSelectAllMode}
                        showCheckBoxesMode={DataConfig.selectionShowCheckBoxesMode}
                    />
                    <RowDragging
                        allowReordering={DataConfig.rowDragging}
                        showDragIcons={DataConfig.rowDraggingShowDragIcons}
                        onReorder={onReorder}
                    />
                    <Export enabled={DataConfig.export} allowExportSelectedData={DataConfig.exportAllowExportSelectedData} />
                    <LoadPanel enabled={DataConfig.loadPanel} />
                    <Summary>
                        {DataConfig.totalSummary && DataConfig.totalSummary.map((sum, index) =>
                            <TotalItem
                                key={index}
                                column={sum.column}
                                summaryType={sum.summaryType}
                                customizeText={(e) => `${sum?.customizeText || ''} ${e.value}`}
                                showInColumn={sum.showInColumn}
                                alignment={sum.alignment}
                            />
                        )}
                        {DataConfig.groupSummary && DataConfig.groupSummary.map((sum, index) =>
                            <GroupItem
                                key={index}
                                column={sum.column}
                                summaryType={sum.summaryType}
                                customizeText={(e) => `${sum?.customizeText || ''} ${e.value}`}
                            />
                        )}
                    </Summary>
                    <Scrolling rowRenderingMode="virtual" />
                    <Paging defaultPageSize={1000000} />
                </DataGrid> :
                <Skeleton active />
            }
        </div>
    );
}

// 树形表格
export const DevextremeTreeList = ({ dataSource, fields, DataConfig, ColumnOptions, DevEvent }) => {
    const [fieldsMapping, setFieldsMapping] = useState()

    // 更改单元格样式
    const onCellPrepared = e => {
        // console.log(e)
        // if (e.column.dataField === "uuid") {
        //     console.log(e.rowType)  // 头部  单元格 底部统计
        //     if (e.data?.num01 > 3000) e.cellElement.style.cssText = "color: white; background-color: red"  // e.cellElement.classList.add("my-class")
        //     if (!e.data?.num01) e.cellElement.style.cssText = "color: white; background-color: #000"
        // }
    }

    const onSelectionChanged = e => {
        DevEvent.emit({ type: 'onSelectionChanged', data: e.selectedRowKeys })
    }

    useMount(async () => {
        fields.forEach(async item => {
            const { isMapping, mappingType, mappingData } = item
            if (isMapping) {
                if (mappingType === 'DataMapping') item.lookupMapping = FieldMapping[mappingData]
                if (mappingType === 'ApiMapping') item.lookupMapping = await API_Mapping[mappingData]()
            }
        })
        setFieldsMapping(fields)
    })

    return (
        <div className='DevextremeTreeList' >
            {fieldsMapping &&
                <TreeList
                    id={new Date().getTime()}
                    keyExpr='uuid'
                    dataStructure="tree"
                    itemsExpr='children'
                    // autoExpandAll={true}
                    dataSource={dataSource}
                    allowColumnReordering={DataConfig.allowColumnReordering}
                    showColumnHeaders={DataConfig.showColumnHeaders}
                    columnMinWidth={DataConfig.columnMinWidth}
                    columnAutoWidth={DataConfig.columnAutoWidth}
                    allowColumnResizing={DataConfig.allowColumnResizing}
                    columnResizingMode={DataConfig.columnResizingMode}
                    repaintChangesOnly={DataConfig.repaintChangesOnly}
                    focusedRowEnabled={DataConfig.focusedRowEnabled}
                    showBorders={DataConfig.showBorders}
                    showRowLines={DataConfig.showRowLines}
                    showColumnLines={DataConfig.showColumnLines}
                    rowAlternationEnabled={DataConfig.rowAlternationEnabled}
                    onCellPrepared={onCellPrepared}
                    onSelectionChanged={onSelectionChanged}
                >
                    {fieldsMapping.map(item =>
                        <Column
                            key={item.dataField}
                            visible={item.visible}
                            caption={item.caption}
                            dataField={item.dataField}
                            cssClass={item.cssClass}
                            alignment={item.alignment}
                            dataType={item.dataType}
                            format={numberFormatting(item.dataType, item.format)}
                            minWidth={item.minWidth}
                            width={item.width}
                            fixed={item.fixed}
                            fixedPosition={item.fixedPosition}
                            allowResizing={item.allowResizing}
                            allowFiltering={item.allowFiltering}
                            allowHeaderFiltering={item.allowHeaderFiltering}
                            allowReordering={item.allowReordering}
                            autoExpandGroup={item.autoExpandGroup}
                            showInColumnChooser={item.showInColumnChooser}
                            allowGrouping={item.allowGrouping}
                        // groupIndex={item.groupIndex}
                        // allowSorting={item.allowSorting}
                        // defaultSortIndex={item.defaultSortIndex}
                        // defaultSortOrder={item.defaultSortOrder}
                        // customizeText
                        // calculateCellValue
                        >
                            {item.isMapping && <Lookup dataSource={item.lookupMapping} valueExpr={item.mappingValue} displayExpr={item.mappingLable} />}
                        </Column>
                    )}
                    <Column
                        cssClass="employee"
                        showInColumnChooser={false}
                        headerCellRender={() => (<div>操作</div>)}
                        fixed={true}
                        width={DataConfig.columnDlyWidth}
                        fixedPosition='right'
                        alignment='center'
                        cellRender={(e) => (
                            <>{ColumnOptions({ data: e.data, fields }).map((item, index) => <ButtonMapping key={index} config={item} />)}</>
                        )}
                    />
                    <SearchPanel visible={DataConfig.searchPanel} />
                    <HeaderFilter visible={DataConfig.headerFilter} />
                    <ColumnFixing enabled={DataConfig.columnFixing} />
                    <Sorting mode={DataConfig.sorting} />
                    <FilterRow visible={DataConfig.filterRow} applyFilter={DataConfig.filterRowApplyFilter} />
                    <ColumnChooser
                        enabled={DataConfig.columnChooser}
                        mode={DataConfig.columnChooserMode}
                    >
                        <Position my="right top" at="right bottom" of=".dx-treelist-column-chooser-button" />
                        <ColumnChooserSearch
                            enabled={DataConfig.columnChooserSearch}
                            editorOptions={{ placeholder: DataConfig.columnChooserSearchPlaceholder }}
                        />
                        <ColumnChooserSelection
                            allowSelectAll={DataConfig.columnChooserSelectionAll}
                            selectByClick={DataConfig.columnChooserSelectionClick}
                            recursive={DataConfig.columnChooserSelectionRecursive}
                        />
                    </ColumnChooser>
                    <Selection
                        mode={DataConfig.selectionMode}
                        allowSelectAll={DataConfig.selectionAllowSelectAll}
                        selectAllMode={DataConfig.selectionSelectAllMode}
                        showCheckBoxesMode={DataConfig.selectionShowCheckBoxesMode}
                    />
                    <Scrolling rowRenderingMode="virtual" />
                    <Paging defaultPageSize={1000000} />
                </TreeList>
            }
        </div >
    )
}

// OLAP数据
export const DevextremePivotGrid = ({ dataSource, fields, DataConfig }) => {
    const pivotRef = useRef()
    const { notification } = App.useApp()
    const [OLAPData, setOLAPData] = useState()

    const { updateDevPivot } = devChartsStore()
    const { send } = useRequest(params => Http({ url: 'getJSONData', params }), { immediate: false })

    useEffect(() => {
        send({ Uuid: `OLAPLayout/${DataConfig.pageUrl}` }).then(res => {
            const fieldsArr = fields.map(item => {
                const data = res.find(v => v.dataField === item.dataField) || {}
                return {
                    ...data,
                    caption: item.caption,
                    dataField: item.dataField,
                    format: numberFormatting(item.dataType, item.format),
                    summaryType: item.summaryType,
                }
            })
            const olapMapping = { fields: fieldsArr.sort((a, b) => a.sortId - b.sortId), store: dataSource }
            setOLAPData(new PivotGridDataSource(olapMapping))  // 序列化数组
        }).catch(() => {
            notification.info({ key: 'optionsInfo', showProgress: true, message: '暂无布局!', description: '发布前请先保存默认布局!' })
            const fieldsArr = fields.map(item => ({ caption: item.caption, dataField: item.dataField, summaryType: item.summaryType }))
            const olapMapping = { fields: fieldsArr.sort((a, b) => a.sortId - b.sortId), store: dataSource }
            setOLAPData(new PivotGridDataSource(olapMapping))  // 序列化数组
        })
    }, [dataSource])

    useEffect(() => {
        updateDevPivot(pivotRef)
    }, [pivotRef])

    const onExporting = e => {
        const workbook = new Workbook()
        const worksheet = workbook.addWorksheet('Sales')
        exportPivotGrid({ component: e.component, worksheet }).then(() => {
            workbook.xlsx.writeBuffer().then((buffer) => saveAs(new Blob([buffer], { type: 'application/octet-stream' }), 'Sales.xlsx'))
        })
    }

    return (
        <div className='DevextremeDataGrid' >
            <PivotGrid
                id={new Date().getTime()}
                ref={pivotRef}
                dataSource={OLAPData}
                allowSorting={DataConfig.allowSorting}
                allowSortingBySummary={DataConfig.allowSortingBySummary}
                allowFiltering={DataConfig.allowFiltering}
                allowExpandAll={DataConfig.allowExpandAll}
                showBorders={DataConfig.showBorders}
                rowHeaderLayout={DataConfig.rowHeaderLayout}
                showTotalsPrior={DataConfig.showTotalsPrior}
                dataFieldArea={DataConfig.dataFieldArea}
                onExporting={onExporting}
                showColumnTotals={DataConfig.showColumnTotals}
                showColumnGrandTotals={DataConfig.showColumnGrandTotals}
                showRowTotals={DataConfig.showRowTotals}
                showRowGrandTotals={DataConfig.showRowGrandTotals}
            >
                <FieldChooser
                    enabled={DataConfig.fieldChooserEnabled}
                    title={DataConfig.fieldChooserTitle}
                    layout={DataConfig.fieldChooserLayout}
                    width='60vh'
                    height='80vh'
                    allowSearch={DataConfig.fieldChooserAllowSearch}
                    applyChangesMode={DataConfig.fieldChooserApplyChangesMode}
                />
                <FieldPanel
                    visible={DataConfig.fieldPanelVisible}
                    allowFieldDragging={DataConfig.fieldPanelAllowFieldDragging}
                    showColumnFields={DataConfig.fieldPanelShowColumnFields}
                    showRowFields={DataConfig.fieldPanelShowRowFields}
                    showDataFields={DataConfig.fieldPanelShowDataFields}
                    showFilterFields={DataConfig.fieldPanelShowFilterFields}
                />
                <Export enabled={DataConfig.export} />
                <Scrolling mode="virtual" />
                <StateStoring enabled={DataConfig.stateStoringEnabled} type="sessionStorage" storageKey={DataConfig.pageUrl} />
            </PivotGrid>
        </div>


    )
}

export const DevextremeTemplate = ({ dataSource, config, DevEvent, ColumnOptions, selectRowkeys }) => {
    const DevextremeMapping = { data: DevextremeDataGrid, tree: DevextremeTreeList, olap: DevextremePivotGrid, multilayer: DevextremeMultilayerGrid }
    const { tableConfig, fieldConfig } = config
    const Template = useMemo(() => { return DevextremeMapping[tableConfig.tableType] }, [tableConfig])

    return (
        <Template
            dataSource={dataSource}
            DevEvent={DevEvent}
            DataConfig={tableConfig}
            fields={fieldConfig || []}
            selectRowkeys={selectRowkeys}
            ColumnOptions={ColumnOptions && ColumnOptions}
        />
    )
}